import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:kq_flutter_core_widget/config/kq_core_global.dart';
import '../resources/kq_theme_colors.dart';
import '../resources/l10n/kq_intl.dart';
import '../widgets/calendar/kq_calendar.dart';
import '../widgets/datePicker/kq_picker.dart';
import '../widgets/dialog/kq_choose_dialog.dart';
import '../widgets/dialog/kq_confirm_dialog.dart';
import '../widgets/dialog/kq_custom_dialog.dart';
import '../widgets/dialog/kq_date_picker_dialog.dart';
import '../widgets/dialog/kq_input_dialog.dart';
import '../widgets/dialog/kq_list_dialog.dart';
import '../widgets/dialog/kq_msg_dialog.dart';
import '../widgets/dialog/kq_reason_dialog.dart';
import '../widgets/dialog/kq_step_number_dialog.dart';
import '../widgets/formItem/kq_radio_item_view.dart';

/// 通用对话框，简化调用过程
class KqDialog {
  ///消息对话框
  ///
  /// 顶部标题
  /// 中间内容
  /// 底部1个按钮-我知道了
  static showMsgDialog(
      {String? title,
      required String msg,
      TextAlign? msgTextAlign,
      String? btnText,
      bool barrierDismissible = true,
      GestureTapCallback? onBtnTap,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.25),
        builder: (context) {
          return KqMsgDialog(
            titleString: title,
            msg: msg,
            btnText: btnText ?? KqIntl.currentResource.known,
            msgTextAlign: msgTextAlign,
            onBtnTap: () {
              Navigator.pop(context);
              onBtnTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 确认对话框，
  ///
  /// 顶部标题
  /// 中间内容
  /// 底部两个按钮-取消和确定
  static showConfirmDialog(
      {String? title,
      required String msg,
      TextAlign? msgTextAlign,
      String? leftBtnText,
      String? rightBtnText,
      double? titleFontSize,
      double? msgFontSize,
      Color? msgColor,
      bool barrierDismissible = true,
      GestureTapCallback? onCancel,
      GestureTapCallback? onConfirm,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.25),
        builder: (context) {
          return KqConfirmDialog(
            titleString: title,
            msg: msg,
            msgTextAlign: msgTextAlign,
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            titleFontSize: titleFontSize,
            msgFontSize: msgFontSize,
            msgColor: msgColor,
            onLeftBtnTap: () {
              Navigator.pop(context);
              onCancel?.call();
            },
            onRightBtnTap: () {
              Navigator.pop(context);
              onConfirm?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 输入对话框
  ///
  /// defValue : 默认值
  /// maxLines : 最大行数，默认1
  /// multiline : 是否支持多行，默认false
  /// allowEmpty : 内容为空是否允许确定，默认true
  /// inputTextAlign : 输入框内容对齐方式
  /// inputFormatters : 输入框内容格式限制
  /// inputType : 键盘类型
  /// autoDismissWhenTapMiddle : 是否点击中间按钮自动关闭对话框，默认true
  /// onEmptyCallback : allowEmpty = false 时，输入为空提交回调
  /// onConfirm : 确认点击回调
  static showInputDialog(String title,
      {String? subTitle,
      Color? subTitleColor,
      double? subTitleFontSize,
      String? placeHolder,
      String? defValue,
      bool multiline = false,
      bool allowEmpty = true,
      bool barrierDismissible = true,
      TextAlign? inputTextAlign,
      TextInputType? inputType,
      String? leftBtnText,
      String? rightBtnText,
      String? middleBtnText,
      int? maxCharCount,
      List<TextInputFormatter>? inputFormatters,
      bool autoDismissWhenTapLeft = true,
      bool autoDismissWhenTapRight = true,
      bool autoDismissWhenTapMiddle = true,
      Function()? onEmptyCallback, //allowEmpty = false 时，输入为空提交回调
      Function(String value)? onLeftBtnClick,
      Function(String value)? onMiddleBtnClick,
      required Function(String value) onConfirm,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.25),
        builder: (context) {
          return KqInputDialog(
            defValue: defValue,
            titleString: title,
            subTitleString: subTitle,
            subTitleColor: subTitleColor,
            subTitleFontSize: subTitleFontSize,
            multiline: multiline,
            placeHolder: placeHolder,
            inputType: inputType ??
                (multiline ? TextInputType.multiline : TextInputType.text),
            inputTextAlign: inputTextAlign,
            inputFormatters: inputFormatters,
            maxLines: 5,
            maxCharCount: maxCharCount,
            editController: TextEditingController(),
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            middleBtnText: middleBtnText,
            onLeftBtnTap: (value) {
              if (onLeftBtnClick == null) {
                Navigator.pop(context);
              } else {
                if (autoDismissWhenTapLeft) {
                  Navigator.pop(context);
                }
                onLeftBtnClick.call(value);
              }
            },
            onMiddleBtnTap: (value) {
              if (autoDismissWhenTapMiddle) {
                Navigator.pop(context);
              }
              onMiddleBtnClick?.call(value);
            },
            onRightBtnTap: (value) {
              if (allowEmpty || value.isNotEmpty) {
                if (autoDismissWhenTapRight) {
                  Navigator.pop(context);
                }
                onConfirm(value);
              } else {
                if (onEmptyCallback != null) {
                  onEmptyCallback();
                }
              }
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 列表对话框
  static showListDialog<T>(List<T> items,
      {String? customTitle,
      bool barrierDismissible = true,
      String Function(int index, T item)? nameConvert,
      Widget Function(int index, T item)? customItemBuilder,
      Function(int index, T item)? callback,
      Function()? onDismiss}) {
    if (items.isEmpty) {
      return;
    }
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.25),
        builder: (context) {
          return KqListDialog(
              items: items,
              nameConvert: nameConvert,
              customTitle: customTitle,
              customItemBuilder: customItemBuilder,
              callback: (index, item) {
                Navigator.pop(context);
                if (callback != null) {
                  callback(index, item);
                }
              });
        }).then((value) => onDismiss?.call());
  }

  ///类似原因的对话框
  static showReasonDialog(
      {required String title,
      required String Function(int index)? renderTitleCallback,
      required int? totalCount,
      String Function(int index)? renderIdCallback,
      String? chosenDataId,
      bool? isShowBottomBtn,
      double? reasonHeight,
      bool isOnlySelect = true,
      GestureTapCallback? onCancel,
      GestureTapCallback? onConfirm,
      Widget? bottomChildWidget,
      Function(int index)? callBack}) {
    return showDialog(
        barrierDismissible: true,
        context: KqCoreGlobal.globalContext,
        barrierColor: Colors.black.withOpacity(0.25),
        builder: (BuildContext context) {
          return KqReasonDialog(
            title: title,
            renderTitleCallback: renderTitleCallback,
            renderIdCallback: renderIdCallback,
            chosenDataId: chosenDataId,
            totalCount: totalCount,
            isShowBottomBtn: isShowBottomBtn,
            bottomChildWidget: bottomChildWidget,
            reasonHeight: reasonHeight,
            onLeftBtnTap: () {
              Navigator.pop(context);
              onCancel?.call();
            },
            onRightBtnTap: () {
              Navigator.pop(context);
              onConfirm?.call();
            },
            callBack: ((index) {
              if (isShowBottomBtn != true) {
                Navigator.pop(context);
              }
              if (callBack != null) {
                callBack(index);
              }
            }),
          );
        }).then((value) {});
  }

  /// 日期选择
  static showDatePicker(
    String title, {
    bool barrierDismissible = true,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    String? dateFormat = "yyyy年,MM月,dd日",
    bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    return showDialog(
      context: KqCoreGlobal.globalContext,
      barrierDismissible: barrierDismissible,
      barrierColor: Colors.black.withOpacity(0.25),
      builder: (context) => KqDatePickerDialog(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.datetime,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
          dateFormat: dateFormat,
          onConfirm: onConfirm,
          onCancel: onCancel,
          onChange: onChange),
    ).then((value) => {onDismiss?.call()});
  }

  /// 时间选择对话框
  static showTimePicker(
    String title, {
    bool barrierDismissible = true,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    String? dateFormat = "HH时:mm分:ss秒",
    bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    return showDialog(
      context: KqCoreGlobal.globalContext,
      barrierDismissible: barrierDismissible,
      barrierColor: Colors.black.withOpacity(0.25),
      builder: (context) => KqDatePickerDialog(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.time,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
          dateFormat: dateFormat,
          onConfirm: onConfirm,
          onCancel: onCancel,
          onChange: onChange),
    ).then((value) => {onDismiss?.call()});
  }

  /// 日期时间选择对话框
  static showDateTimePicker(
    String title, {
    bool barrierDismissible = true,
    bool withSecond = true,
    bool withMinute = true,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    String? dateFormat,
    bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    dateFormat ??=
        'yyyy年,MM月,dd日,HH时${withMinute ? ':mm分' : ''}${withSecond ? ':ss秒' : ''}';
    return showDialog(
      context: KqCoreGlobal.globalContext,
      barrierDismissible: barrierDismissible,
      barrierColor: Colors.black.withOpacity(0.25),
      builder: (context) => KqDatePickerDialog(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.datetime,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
          dateFormat: dateFormat,
          onConfirm: onConfirm,
          onCancel: onCancel,
          onChange: onChange),
    ).then((value) => {onDismiss?.call()});
  }

  /// 显示loading
  static void showLoading({String? msg, bool showMask = false}) {
    EasyLoading.show(
        status: msg ?? KqIntl.currentResource.loading,
        maskType:
            showMask ? EasyLoadingMaskType.black : EasyLoadingMaskType.clear);
  }

  /// 关闭loading
  static void closeLoading() {
    EasyLoading.dismiss();
  }

  // 自定义弹窗
  static showCustomDialog(
      {String? title,
      required Widget customWidget,
      Widget? Function(BuildContext context, GestureTapCallback? onCancel)?
          customBtnWidget,
      double? width,
      String? leftBtnText,
      String? rightBtnText,
      bool barrierDismissible = true,
      GestureTapCallback? onLeftTap,
      GestureTapCallback? onRightTap,
      bool isShowLeft = false,
      bool isShowRight = false,
      bool autoDismissWhenTapLeft = true,
      bool autoDismissWhenTapRight = true,
      bool showClose = false,
      double? topPadding,
      double? bottomPadding,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return KqCustomDialog(
            titleString: title,
            customWidget: customWidget,
            customBtnWidget: customBtnWidget?.call(context, onLeftTap),
            width: width,
            leftBtnText: leftBtnText,
            //左侧灰色
            rightBtnText: rightBtnText,
            isShowLeft: isShowLeft,
            isShowRight: isShowRight,
            showClose: showClose,
            topPadding: topPadding,
            bottomPadding: bottomPadding,
            onLeftBtnTap: () {
              if (autoDismissWhenTapLeft) {
                Navigator.pop(context);
              }
              onLeftTap?.call();
            },
            onRightBtnTap: () {
              if (autoDismissWhenTapRight) {
                Navigator.pop(context);
              }
              onRightTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  // 自定义选择框
  static showChooseDialog(
      {required String title,
      required List<KqChooseData> items,
      bool isSingleChoose = true,
      List<String>? chosenIds,
      bool barrierDismissible = true,
      Function(List<KqChooseData> chooses)? callback,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return StatefulBuilder(builder: ((context, state) {
            return KqChooseDialog(
              title: title,
              items: items,
              state: state,
              isSingleChoose: isSingleChoose,
              chosenIds: chosenIds,
              callback: ((chooses) {
                Navigator.pop(context);
                callback?.call(chooses);
              }),
            );
          }));
        }).then((value) => onDismiss?.call());
  }

  /// 班次日历选择
  ///
  /// [shifts]班次数据，[initialShift]默认选中班次
  ///
  static showDataTimeShiftDialog<T extends GetxController>(
    KQSelectMode selectMode, {
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    DateTime? rangeStart,
    DateTime? rangeEnd,
    List<RadioData>? shifts,
    RadioData? initialShift,
    String? local = 'zh',
    Function(DateTime? startDate, DateTime? endDate, RadioData? shift)?
        onConfirm,
  }) {
    DateTime? startDate;
    DateTime? endDate;
    if (selectMode == KQSelectMode.range) {
      startDate = rangeStart;
      endDate = rangeEnd;
    } else {
      startDate = endDate = initialDateTime;
    }

    RadioData? shift = initialShift == null
        ? null
        : shifts?.firstWhereOrNull(
            (element) => element.itemId == initialShift.itemId);

    Widget? result;
    if (shifts != null && shifts.isNotEmpty) {
      result = StatefulBuilder(
        builder: (context, setState) {
          Widget result = ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: shifts.length,
            itemBuilder: (BuildContext context, int index) {
              RadioData modelNew = shifts[index];
              bool chosen = modelNew == shift;

              Widget result = Text(
                modelNew.item,
                style: TextStyle(
                  color: chosen ? KqThemeColors.bgWhite : KqThemeColors.text26,
                  fontSize: 24.sp,
                ),
              );
              result = Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.r),
                  child: result);
              result = Container(
                alignment: Alignment.center,
                color: chosen ? KqThemeColors.bgBlue : KqThemeColors.bgDefault,
                constraints: BoxConstraints(minWidth: 120.r, minHeight: 50.r),
                child: result,
              );

              result = InkWell(
                onTap: () {
                  shift = modelNew;
                  setState.call(() {});
                },
                child: result,
              );
              return result;
            },
          );

          result = SizedBox(height: 50.r, child: result);
          result = ScrollConfiguration(
              behavior: const ScrollBehavior().copyWith(overscroll: false),
              child: result);
          return result;
        },
      );
      result = Padding(
          padding: EdgeInsets.only(left: 20.r, right: 20.r, top: 10.r),
          child: result);
    }

    result = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        KqCalendar(
          locale: local,
          selectMode: selectMode,
          focusedDay: initialDateTime,
          selectedDay: initialDateTime,
          rangeStart: rangeStart,
          rangeEnd: rangeEnd,
          limitStartTime: minDateTime,
          limitEndTime: maxDateTime,
          selectedRangeDateCallback: (startDate2, endDate2) {
            startDate = startDate2;
            endDate = endDate2;
          },
          selectedSingleDateCallback: (date) {
            startDate = endDate = date;
          },
        ),
        if (result != null) result,
        SizedBox(height: 10.r),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            InkWell(
              onTap: () {
                onConfirm?.call(startDate, endDate, shift);
              },
              child: Container(
                alignment: Alignment.center,
                height: 50.r,
                width: 140.r,
                color: KqThemeColors.bgBlue,
                child: Text(KqIntl.currentResource.ok,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: KqThemeColors.bgWhite, fontSize: 24.sp)),
              ),
            ),
            SizedBox(width: 20.r),
          ],
        )
      ],
    );

    result = SizedBox(width: 900.r, child: result);
    return showCustomDialog(customWidget: result);
  }

  /// 数字步进对话框
  ///
  /// 两边加减号，中间输入框的对话框
  static showStepNumberDialog(
      {String? title,
      bool barrierDismissible = true,
      String? leftBtnText,
      String? rightBtnText,
      num min = 0,
      num? max,
      num step = 1,
      bool decimal = false,
      bool autoDismissWhenTapLeft = true,
      bool autoDismissWhenTapRight = true,
      TextEditingController? editingController,
      Function(String value)? onLeftBtnClick,
      required Function(String value) onRightBtnClick,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqStepNumberDialog(
            titleString: title,
            editController: editingController ??
                TextEditingController(text: min.toString()),
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            min: min,
            max: max,
            step: step,
            decimal: decimal,
            onLeftBtnTap: (value) {
              if (onLeftBtnClick == null) {
                Navigator.pop(context);
              } else {
                if (autoDismissWhenTapLeft) {
                  Navigator.pop(context);
                }
                onLeftBtnClick.call(value);
              }
            },
            onRightBtnTap: (value) {
              if (autoDismissWhenTapRight) {
                Navigator.pop(context);
              }
              onRightBtnClick(value);
            },
          );
        }).then((value) => onDismiss?.call());
  }
}
